package com.xz.web.controller.diagnosisOrder;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xz.common.annotation.Log;
import com.xz.common.core.controller.BaseController;
import com.xz.common.core.domain.AjaxResult;
import com.xz.common.core.domain.model.LoginUser;
import com.xz.common.core.page.TableDataInfo;
import com.xz.common.enums.BusinessType;
import com.xz.common.exception.ServiceException;
import com.xz.common.service.ISysAccessoryService;
import com.xz.common.utils.SecurityUtils;
import com.xz.common.utils.poi.ExcelUtil;
import com.xz.diagnosisOrder.domain.DiagnosisOrder;
import com.xz.diagnosisOrder.domain.DiagnosisRefundOrder;
import com.xz.diagnosisOrder.domain.DiagnosisRefundOrderDetail;
import com.xz.diagnosisOrder.domain.DiagnosisTreatmentOrder;
import com.xz.diagnosisOrder.dto.DiagnosisOrderSaveDto;
import com.xz.diagnosisOrder.dto.DiagnosisRefundOrderConfirmDto;
import com.xz.diagnosisOrder.enums.PaymentStatusEnum;
import com.xz.diagnosisOrder.service.IDiagnosisOrderService;
import com.xz.diagnosisOrder.service.IDiagnosisRefundOrderDetailService;
import com.xz.diagnosisOrder.service.IDiagnosisRefundOrderService;
import com.xz.diagnosisOrder.service.IDiagnosisTreatmentOrderService;
import com.xz.diagnosisOrder.vo.DiagnosisRefundOrderDetailVo;
import com.xz.diagnosisOrder.vo.DiagnosisRefundOrderListVo;
import com.xz.diagnosisOrder.vo.DiagnosisRefundOrderVo;
import com.xz.expense.domain.ExpenseBill;
import com.xz.expense.mapper.ExpenseBillMapper;
import com.xz.patient.domain.PatientInfo;
import com.xz.patient.mapper.PatientInfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

/**
 * 挂号/诊疗退费单Controller
 *
 * @author xz
 * @date 2024-03-27
 */
@RestController
@RequestMapping("/diagnosisOrder/refundOrder")
public class DiagnosisRefundOrderController extends BaseController {
  @Autowired
  private IDiagnosisRefundOrderService diagnosisRefundOrderService;
  @Autowired
  private IDiagnosisRefundOrderDetailService diagnosisRefundOrderDetailService;
  @Autowired
  private IDiagnosisOrderService diagnosisOrderService;
  @Autowired
  private IDiagnosisTreatmentOrderService diagnosisTreatmentOrderService;
  @Autowired
  private PatientInfoMapper patientInfoMapper;
  @Autowired
  private ISysAccessoryService SysAccessoryService;

  /**
   * 查询挂号/诊疗退费单列表
   */
  //@PreAuthorize("@ss.hasPermi('diagnosisOrder:refundOrder:list')")
  @GetMapping("/list")
  public TableDataInfo list(DiagnosisRefundOrder diagnosisRefundOrder) {
    startPage();
    List<DiagnosisRefundOrderListVo> list = diagnosisRefundOrderService.selectDiagnosisRefundOrderVoList(diagnosisRefundOrder);
    return getDataTable(list);
  }

  /**
   * 导出挂号/诊疗退费单列表
   */
  //@PreAuthorize("@ss.hasPermi('diagnosisOrder:refundOrder:export')")
  @Log(title = "挂号/诊疗退费单", businessType = BusinessType.EXPORT)
  @GetMapping("/export")
  public AjaxResult export(DiagnosisRefundOrder diagnosisRefundOrder) {
    List<DiagnosisRefundOrderListVo> list = diagnosisRefundOrderService.selectDiagnosisRefundOrderVoList(diagnosisRefundOrder);
    ExcelUtil<DiagnosisRefundOrderListVo> util = new ExcelUtil<DiagnosisRefundOrderListVo>(DiagnosisRefundOrderListVo.class);
    return util.exportExcel(list, "退费记录列表数据");
  }

  /**
   * 获取挂号/诊疗退费单详细信息
   */
  //@PreAuthorize("@ss.hasPermi('diagnosisOrder:refundOrder:query')")
  @GetMapping(value = "detail/{id}")
  public AjaxResult getInfo(@PathVariable("id") Long id) {
    DiagnosisRefundOrder refundOrder = diagnosisRefundOrderService.selectDiagnosisRefundOrderById(id);

    if (null == refundOrder) {
      return AjaxResult.success();
    }
    DiagnosisRefundOrderVo vo = new DiagnosisRefundOrderVo();
    BeanUtils.copyProperties(refundOrder, vo);
    //填充客户信息
    PatientInfo patientInfo = patientInfoMapper.selectById(refundOrder.getPatientId());
    if (null != patientInfo) {
      vo.setPatientName(patientInfo.getPatientName());
      vo.setPhoneNumber(patientInfo.getPhoneNumber());
      vo.setSex(patientInfo.getSex());
      vo.setBirthday(patientInfo.getBirthday());
    }

    // 填充详情
    LambdaQueryWrapper<DiagnosisRefundOrderDetail> wrapper = Wrappers.lambdaQuery(DiagnosisRefundOrderDetail.class);
    wrapper.eq(DiagnosisRefundOrderDetail::getRefundOrderId, id);
    List<DiagnosisRefundOrderDetail> orders = diagnosisRefundOrderDetailService.getBaseMapper().selectList(wrapper);
    if (CollectionUtils.isEmpty(orders)) {
      return AjaxResult.success(vo);
    }
    //转化详情
    orders.forEach(order -> {
      DiagnosisRefundOrderDetailVo voDetail = new DiagnosisRefundOrderDetailVo();
      BeanUtils.copyProperties(order, voDetail);
      vo.getDetails().add(voDetail);
    });

    //查找审批备注和详情
    vo.setVoucherRemark(refundOrder.getRemark());
    List<String> urlList = SysAccessoryService.selectSupplierAccessoryUrlList(id.toString(),5);
    vo.setVoucherUrlList(urlList);

    return AjaxResult.success(vo);
  }

  @GetMapping("init/{ids}")
  public AjaxResult initPage(@PathVariable Long[] ids, Integer type) {
    if (null == type) {
      throw new ServiceException("参数异常");
    }
    DiagnosisRefundOrderVo vo = new DiagnosisRefundOrderVo();

    //挂号单
    if (type.equals(1)) {
      DiagnosisOrder order = diagnosisOrderService.selectDiagnosisOrderById(ids[0]);
      if (null == order) {
        throw new ServiceException("单据不存在或已删除");
      }
      if (!PaymentStatusEnum.PAID.eq(order.getPaymentStatus())) {
        throw new ServiceException("单据状态发生变化，请刷新后重新选择");
      }
      //主数据转化
      DiagnosisRefundOrder refundOrder = diagnosisRefundOrderService.initOrder(diagnosisOrderService.selectDiagnosisOrderById(ids[0]));
      BeanUtils.copyProperties(refundOrder, vo);
      //填充客户信息
      PatientInfo patientInfo = patientInfoMapper.selectById(order.getPatientId());
      if (null != patientInfo) {
        vo.setPatientName(patientInfo.getPatientName());
        vo.setPhoneNumber(patientInfo.getPhoneNumber());
        vo.setSex(patientInfo.getSex());
        vo.setBirthday(patientInfo.getBirthday());
      }
      //因为是待提交，所以要保证这些字段是默认值
      vo.setStatus(PaymentStatusEnum.PENDING_REFUND.getStatus());
      //详情数据转化
      DiagnosisRefundOrderDetail refundOrderDetail = diagnosisRefundOrderDetailService.initDetail(order, refundOrder);
      DiagnosisRefundOrderDetailVo voDetail = new DiagnosisRefundOrderDetailVo();
      BeanUtils.copyProperties(refundOrderDetail, voDetail);
      //填充详情数据
      voDetail.setId(ids[0]);
      vo.getDetails().add(voDetail);
    }
    // 就诊单
    else if (type.equals(2)) {

      //List<DiagnosisTreatmentOrder> orders = diagnosisTreatmentOrderService.getBaseMapper().selectBatchIds(Arrays.asList(ids));
      List<DiagnosisTreatmentOrder> orders = diagnosisTreatmentOrderService.selectById(ids);
      if (CollectionUtils.isEmpty(orders) || orders.size() != ids.length) {
        throw new ServiceException("单据发生变化，请重新选择");
      }
      DiagnosisTreatmentOrder orderFrist = orders.get(0);
      //校验创建人，创建部门
      orders.forEach(order -> {
        if (!order.getPatientId().equals(orderFrist.getPatientId()) || !order.getDeptId().equals(orderFrist.getDeptId())) {
          throw new ServiceException("请选择相同的客户，门店单据");
        }
        if (!PaymentStatusEnum.PAID.eq(order.getPaymentStatus())) {
          throw new ServiceException("单据状态发生变化，请刷新后重新选择");
        }
      });
      //主数据转化
      DiagnosisRefundOrder refundOrder = diagnosisRefundOrderService.initOrder(orders);
      BeanUtils.copyProperties(refundOrder, vo);
      //因为是待提交，所以要保证这些字段是默认值
      vo.setStatus(PaymentStatusEnum.PENDING_REFUND.getStatus());
      //填充客户信息
      PatientInfo patientInfo = patientInfoMapper.selectById(refundOrder.getPatientId());
      if (null != patientInfo) {
        vo.setPatientId(patientInfo.getId());
        vo.setPatientName(patientInfo.getPatientName());
        vo.setPhoneNumber(patientInfo.getPhoneNumber());
        vo.setSex(patientInfo.getSex());
        vo.setBirthday(patientInfo.getBirthday());
      }
      //详情数据转化
      orders.forEach(order -> {
        DiagnosisRefundOrderDetail refundOrderDetail = diagnosisRefundOrderDetailService.initOrderDetail(order, null);
        DiagnosisRefundOrderDetailVo voDetail = new DiagnosisRefundOrderDetailVo();
        BeanUtils.copyProperties(refundOrderDetail, voDetail);
        voDetail.setId(order.getId());
        vo.getDetails().add(voDetail);
      });
    }
    return AjaxResult.success(vo);
  }

  /**
   * 取消退费
   */
  @Log(title = "挂号/诊疗退费单", businessType = BusinessType.UPDATE)
  @PutMapping("/cancel/{id}")
  public AjaxResult cancelOrderById(@PathVariable("id") Long id) {
    return toAjax(diagnosisRefundOrderService.cancelOrderById(id));
  }

  /**
   * 确认退费
   */
  @Log(title = "挂号/诊疗退费单", businessType = BusinessType.UPDATE)
  @PutMapping("/confirm")
  public AjaxResult cancelOrderById(@Valid @RequestBody DiagnosisRefundOrderConfirmDto dto) {
    return toAjax(diagnosisRefundOrderService.confirmOrder(dto));
  }
}
